package logmngr;

import java.io.*;

/**
 * 
 * @author pavelroi
 *
 * Used primarily to log 
 * Correct Usage: GetLogger(), init() on first use, destroy() on last use.
 */
public class LogMngr {

	//=== Fields ===
	private static 	LogMngr			logger = null;
	private			PrintWriter		pw;
	private			boolean			isInit;
	
	//=== Constructors ===
	/**
	 * Overwrite the default constructor
	 */
	private LogMngr()
	{	// use to create an instance with System's default err stream
		init();
		// on first instance, set false to enforce user to initialize 
		isInit = false; 
	}
	
	//=== Methods ===
	public synchronized void writeLog(LogType type, String msg)
	{
		if(isInit)
		{
			pw.write(type.toString() + " " + msg);
			pw.flush();
		}
		else
		{
			//System.err.println("Uninitialized logger");
		}
	}
	
	public synchronized static LogMngr getLogger()
	{
		if(logger == null)
		{
			logger = new LogMngr();
		}
		return logger;
	}
	
	public void init()
	{
		if(!isInit)
		{
			pw = new PrintWriter(System.err);
			isInit = true;
		}
	}
	
	public void init(File logFile)
	{
		if(!isInit)
		{
			try
			{
				pw = new PrintWriter(logFile);
			} 
			catch(FileNotFoundException fnfex){
				System.err.println("Failed opening file: " + logFile.getAbsolutePath());
				fnfex.printStackTrace();
			}
			isInit = true;
		}
	}
	
	public void init(String filePath)
	{
		File logFile = null;
		try{
			logFile = new File(filePath);
			if(!logFile.exists())
				logFile.createNewFile();
			if(logFile == null || !logFile.canWrite())
			{
				init();
				writeLog(LogType.Err, "Unable to open log file for writing " + filePath);
			}
			else
			{
				init(logFile);
			}
		}
		catch(IOException ioex)
		{
			init();
			writeLog(LogType.Err, "Unable to open log file for writing " + filePath);
		}
	}
	
	
	/**
	 * Call destroy only when done using stream
	 */
	public void destroy()
	{
		if(pw != null)
			pw.close();
		pw = null;
		isInit = false;
	}
	
	
}
